package wikigearsconnector.connect.customrequesentity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.methods.multipart.PartSource;

public class CustomStreamPartSource implements PartSource {

	private byte[] content;
	private String fileName;

	public CustomStreamPartSource(String fileName, InputStream is) {
		initArray(is);
		this.fileName = fileName;
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public InputStream createInputStream() throws IOException {
		return new ByteArrayInputStream(content);
	}

	public String getFileName() {
		return fileName;
	}

	public long getLength() {
		return content.length;
	}

	private void initArray(InputStream is) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		byte[] tmp = new byte[4096];
		int i = 0;

		try {
			while ((i = is.read(tmp)) >= 0) {
				bos.write(tmp,0,i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		content = bos.toByteArray();
		try {
			bos.close();
		} catch (IOException e) {			
			e.printStackTrace();
		}

	}

}
